/**
 * Copyright(c) 2014 Xunton Solutions
 *
 * History:
 *   14-12-26 下午5:32 Created by dwzhang
 */
package com.jade.modules.software.impl;

import java.util.List;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.jade.framework.base.criterion.Criteria;
import com.jade.framework.base.criterion.sql.SqlUtils;
import com.jade.framework.base.util.PagingList;
import com.jade.modules.software.Software;
import com.jade.modules.software.SoftwareDao;
import com.jade.modules.software.SoftwareException;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;

/**
 * 采用JPA方式实现的软件包数据接口。
 *
 * @author <a href="mailto:dwzhang@xunton.com">dwzhang</a> 
 * @version 1.0 14-12-26 下午5:32
 */
//@Named ("module_softwareDao")
public class JpaSoftwareDao
        implements SoftwareDao
{
    @PersistenceContext (unitName = "default")
    protected EntityManager entityManager;

    @Caching (evict = {@CacheEvict (value = "module.software.g", key = "#software.id"),
            @CacheEvict (value = "module.software.l", allEntries = true),
            @CacheEvict (value = "module.software.q", allEntries = true)})
    public void addSoftware(Software software)
            throws SoftwareException
    {
        entityManager.persist(software);
    }

    @Caching (evict = {@CacheEvict (value = "module.software.g", key = "#software.id"),
            @CacheEvict (value = "module.software.l", allEntries = true),
            @CacheEvict (value = "module.software.q", allEntries = true)})
    public void updateSoftware(Software software)
            throws SoftwareException
    {
        entityManager.merge(software);
    }

    @Caching (evict = {@CacheEvict (value = "module.software.g", key = "#software.id"),
            @CacheEvict (value = "module.software.l", allEntries = true),
            @CacheEvict (value = "module.software.q", allEntries = true)})
    public void removeSoftware(Software software)
            throws SoftwareException
    {
        Software old = entityManager.find(Software.class, software.getId());
        if (old != null) {
            entityManager.remove(old);
        }
    }

    @Cacheable (value = "module.software.g", key = "#id")
    public Software getSoftware(long id)
    {
        return entityManager.find(Software.class, id);
    }

    @Cacheable (value = "module.software.l", key = "#criteria")
    public List<Software> listSoftware(Criteria criteria)
    {
        return SqlUtils.sqlQueryWithoutCount(SQL_SOFT, entityManager, criteria);
    }

    @Cacheable (value = "module.software.q", key = "#criteria")
    public PagingList<Software> querySoftware(Criteria criteria)
    {
        return SqlUtils.sqlQuery(SQL_SOFT, entityManager, criteria);
    }

    protected static final String SQL_SOFT = "SELECT software FROM com.jade.modules.software.Software software";
}
